<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>salvo</title>
</head>
{% include "user_list_frag.html" %}
<script defer src="assets/js/tailwindcss.js"></script>
<script defer src="assets/js/sweetalert2.js"></script>
<script defer src="assets/js/alpinejs.js"></script>
<script>
    function userForm() {
        return {
            users: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            searchUsername: '',
            fetchData() {
                const params = new URLSearchParams({
                    page: this.currentPage,
                    size: this.pageSize,
                    username: this.searchUsername
                });
                fetch(`/api/users?${params.toString()}`)
                    .then((response) => {
                        if (!response.ok) {
                            throw new Error("Network response was not ok");
                        }
                        return response.json();
                    })
                    .then((data) => {
                        this.users = data.data;
                        this.total = data.total;
                    })
                    .catch((error) => {
                        console.error(
                            "There has been a problem with your fetch operation:",
                            error
                        );
                    });
            },
            search() {
                this.currentPage = 1;
                this.fetchData();
            },
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.fetchData();
                }
            },
            nextPage() {
                if (this.currentPage < Math.ceil(this.total / this.pageSize)) {
                    this.currentPage++;
                    this.fetchData();
                }
            },
            addUser() {
                Swal.fire({
                    title: "添加用户",
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "取消",
                    html: `
    <input id="swal-input1" class="swal2-input" placeholder="用户名">
    <input id="swal-input2" class="swal2-input" placeholder="密码" type="password">
    `,
                    preConfirm: () => {
                        return fetch("/api/users", {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            body: JSON.stringify({
                                username: document.getElementById("swal-input1").value,
                                password: document.getElementById("swal-input2").value,
                            }),
                        })
                            .then((response) => {
                                if (!response.ok) {
                                    throw new Error(response.statusText);
                                }
                                this.fetchData();
                                return;
                            })
                            .catch((error) => {
                                Swal.showValidationMessage(`Request failed: ${error}`);
                            });
                    },
                    allowOutsideClick: () => !Swal.isLoading(),
                });
            },
            updateUser(id, currentUsername) {
                Swal.fire({
                    title: "更新",
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "取消",
                    html: `
    <input id="swal-input1" class="swal2-input" placeholder="用户名" value="${currentUsername}">
    <input id="swal-input2" class="swal2-input" placeholder="密码" type="password">
    `,
                    preConfirm: () => {
                        return fetch(`/api/users/${id}`, {
                            method: "PUT",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            body: JSON.stringify({
                                username: document.getElementById("swal-input1").value,
                                password: document.getElementById("swal-input2").value,
                            }),
                        })
                            .then((response) => {
                                if (!response.ok) {
                                    throw new Error(response.statusText);
                                }
                                this.fetchData();
                                return;
                            })
                            .catch((error) => {
                                Swal.showValidationMessage(`Request failed: ${error}`);
                            });
                    },
                    allowOutsideClick: () => !Swal.isLoading(),
                });
            },
            deleteUser(id) {
                Swal.fire({
                    title: "确定删除吗？",
                    text: "此操作无法撤销！",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "取消",
                    preConfirm: () => {
                        return fetch(`/api/users/${id}`, {
                            method: "DELETE",
                        })
                            .then((response) => {
                                if (!response.ok) {
                                    throw new Error(response.statusText);
                                }
                                this.fetchData();
                                return;
                            })
                            .catch((error) => {
                                Swal.showValidationMessage(`Request failed: ${error}`);
                            });
                    },
                    allowOutsideClick: () => !Swal.isLoading(),
                });
            },
        };
    }
</script>
</html>
